#include "geometry.h"

bool raySphereIntersect(const VectorD& sphereCenter, DATA_TYPE sphereRadius, const VectorD& rayOrigin, const VectorD& rayDirection, DATA_TYPE& t0, DATA_TYPE& t1)
{
	//Compute A, B and C coefficients
	VectorD oc = rayOrigin - sphereCenter;
    DATA_TYPE a = rayDirection * rayDirection;
    DATA_TYPE b = 2.f * (oc * rayDirection);
	DATA_TYPE c = oc * oc - sphereRadius * sphereRadius;

    //Find discriminant
    DATA_TYPE disc = b * b - 4 * a * c;
    
    // if discriminant is negative there are no real roots, so return 
    // false as ray misses sphere
    if (disc < 0)
        return false;

    // compute q as described above
    DATA_TYPE distSqrt = sqrt(disc);
    DATA_TYPE q;
    if (b < 0)
        q = (-b - distSqrt) * 0.5;
    else
        q = (-b + distSqrt) * 0.5;

    // compute t0 and t1
    t0 = q / a;
    t1 = c / q;

	// make sure t0 is smaller than t1
    if (t0 > t1)
    {
        // if t0 is bigger than t1 swap them around
        DATA_TYPE temp = t0;
        t0 = t1;
        t1 = temp;
    }

	return true;
}